package com.lingjtx.common.influx.common;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParameterBinder {

    public static String bind(String sql, Map<String, Object> params) {
        // 替换 ${}
        Matcher matcher = Pattern.compile("\\$\\{(\\w+)}").matcher(sql);
        StringBuilder sb = new StringBuilder();
        while (matcher.find()) {
            String value = String.valueOf(params.getOrDefault(matcher.group(1), ""));
            matcher.appendReplacement(sb, value);
        }
        matcher.appendTail(sb);

        // 替换 #{}
        matcher = Pattern.compile("#\\{(\\w+)}").matcher(sb.toString());
        sb = new StringBuilder();
        while (matcher.find()) {
            String value = "'" + String.valueOf(params.getOrDefault(matcher.group(1), "")) + "'";
            matcher.appendReplacement(sb, value);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
